import random

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.views import APIView
from rest_framework.response import Response
from meiduo.utils.ytx_sdk.ytx_sdk.sendSMS import CCP
from rest_framework import exceptions
from celery_tasks.sms.tasks import send_sms_code


class SMSCode(APIView):
    def get(self,request,mobile):
        # 连接redis数据库
        redis_cli = get_redis_connection('sms_code')
        #验证是否发过验证吗
        if redis_cli.get('sms_flag_'+mobile):
            raise exceptions.ValidationError('发送验证码太频繁')

        # 发送_code
        #1.随机生成一个6位数验证码
        sms_code = random.randint(100000,999999)

        # 2.使用管道方式与redis交互
        redis_pipeline = redis_cli.pipeline()
        # 将验证码保存到redis中
        redis_pipeline.setex('sms_code_'+ mobile,60,sms_code)
        # 将是否发送了验证码标识保存到redis中
        redis_pipeline.setex('sms_flag_'+mobile,60,1)
        # 执行redis命令
        redis_pipeline.execute()

        # 发送短信
        # print(sms_code)
        # CCP.sendTemplateSMS(mobile,sms_code,60,1)
        send_sms_code.delay(mobile,sms_code,60,1)
        # 响应
        return Response({'massage','ok'})




